#! -*-coding: utf-8-*-
import threading
import requests

from redis_bilibili import RedisBiliBili
from log import MyLogging

log = MyLogging()

R = RedisBiliBili()


class Download(threading.Thread):  # 继承threading类
    def __init__(self, data, sem):
        super().__init__()  # 继承python的构造方法，这为python2的写法，python3可直接super().__init__()
        self.data = data
        self.sem = sem

    @staticmethod
    def download_video(url, name):
        try:
            video_data = requests.get(url).content  #
            # 图片视频音频文件都是二进制的，用wb进行保存，写入response.content content方法
            with open(f'static/video/{name}.mp4', mode='wb') as f:  # 保存数据
                f.write(video_data)
            log.write_logger(f'{name} 保存成功 static/video/{name}')
            return f'static/video/{name}.mp4'
        except Exception as e:
            log.error_logger(f'{name} 视频 保存失败 {e}')

    @staticmethod
    def download_img(url, name):
        try:
            img_data = requests.get(url).content  #
            # 图片视频音频文件都是二进制的，用wb进行保存，写入response.content content方法
            with open(f'static/img/{name}.png', mode='wb') as f:  # 保存数据
                f.write(img_data)
            log.write_logger(f'{name} 保存成功 static/img/{name}')
            return f'static/img/{name}.png'
        except Exception as e:
            log.error_logger(f'{name} 图片 保存失败 {e}')

    def run(self):
        log.write_logger(f'{self.data["title"]} 线程已启动')
        R.set_msg(
            {
                "title": self.data['title'],
                'tag': self.data['tag'],
                'tid': self.data['tid'],
                'platform': self.data['platform'],
                'timestamp': self.data['timestamp'],
                "hid": self.data['hid'],
                "name": self.data['name'],
                "video": self.data['video'],
                "img": self.data['img'],
                "source": f'https://video.kuaishou.com/short-video/{self.data["v_id"]}',
                "video_path": self.download_video(self.data['video'], self.data['hid']),
                "img_path": self.download_img(self.data['img'], self.data['hid']),
                "desc": self.data['desc']
            }
        )
        self.sem.release()  # 释放线程数，线程数加1


if __name__ == '__main__':
    sem = threading.Semaphore(5)  # 设置可同时执行的最大线程数
    for i in range(50):
        sem.acquire()  # 获得线程，可用线程数减1
        t = Download(i, sem)  # 给执行函数传递值
        t.start()  # 执行函数
